<?php

namespace app\api\controller;

use app\common\model\DayCategory;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Category;
use app\common\model\Growing;
use app\common\model\Leave;
use app\common\model\Singin;
use app\common\model\StudentCopies;
use app\common\model\Usergrowing;
use app\common\model\UserGrowingLike;
use app\common\model\UserSignin;
use app\common\model\Userstudent;
use app\common\model\UserStudentLike;
use fast\Http;
use fast\Random;
use fast\Tree;
use think\Db;
use think\Log;
use think\Validate;
use app\common\model\Category as CategoryModel;

use app\common\model\Growing as GrowingModel;
/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $categorylist = [];


    public function _initialize()
    {
        parent::_initialize();

//
//        $categoryList = collection(CategoryModel::where(['status'=>'normal'])->select())->toArray();
//        Tree::instance()->init($categoryList);
//        $searchlist = [];
//        $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
//        foreach ($result as $k => $v) {
//            $searchlist[] = ['id' => $v['id'], 'name' => $v['name']];
//        }
//        return json($searchlist);
//        exit('777');


//        $this->model = model('app\common\model\Category');
//
//        $tree = Tree::instance();
//        $tree->init(collection($this->model->order('weigh desc,id desc')->select())->toArray(), 'pid');
//        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
//        $categorydata = [0 => ['name' => __('None')]];
//        foreach ($this->categorylist as $k => $v) {
//            $categorydata[$v['id']] = $v;
//        }
//
//
//        var_dump($categorydata);exit;


    }


    public function addinfo()
    {
        $nickName = $this->request->Post('nickName');
        $openid = $this->request->Post('openid');
        $avatarUrl = $this->request->Post('avatarUrl');
        $user_id = $this->request->Post('user_id');

        if (!$user_id || !$openid) {
            return  $this->error(__('Invalid parameters'));
        }

        $user = \app\common\model\User::where(['id'=>$user_id])->find();

        if (empty($user)) {
            return $this->error(__('用户未找到'));
        }

        $user->nickname = $nickName;
        $user->avatar = $avatarUrl;
        $user->openid = $openid;

        $user->save();

        return $this->success('','授权成功');

    }




    /**
     * 会员中心
     */
    public function index()
    {
        $this->relationSearch = true;
        $user_id = $this->request->request('user_id');

        if (empty($user_id)) {
            $this->error(__('用户ID未找到'));
        }

        $user = \app\common\model\User::with(['Category', 'Group'])->find($user_id);

        if($user->group_id == 1){
            $user['teacher_tel'] = $user->mobile;
        }else{

            $teacher = \app\common\model\User::where(['category_id'=>$user->category_id,'group_id'=>1])->find();
            $user['teacher_tel'] = $teacher->mobile;
        }

//        $user['is_info'] = 1;



        $this->success('', $user);
    }

    /**
     * 会员登录
     *
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $mobile = $this->request->Post('account');
        $captcha = $this->request->Post('code');


        if (empty($mobile) || empty($captcha)) {
            $this->error(__('Invalid parameters'));
        }

        if (!Sms::check($mobile, $captcha, 'register')) {
            $this->error(__('Captcha is incorrect'));
        }


        $ret = $this->auth->login($mobile);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];

            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }


    }




    /**
     * 会员登录
     *
     * @param string $account 账号
     * @param string $password 密码
     */
    public function wxcode()
    {
        $code = $this->request->Post('code');
        $user_id = $this->request->Post('user_id');
        $appid      = 'wx84a1eb0303bfbd6b';//小程序唯一标识   (在微信小程序管理后台获取)
        $appsecret  = '0719812f92964243cac3894a2e967c6b';//小程序的 app secret (在微信小程序管理后台获取)
        $grant_type = "authorization_code"; //授权（必填）

        if(empty($code)){
            $this->error('code不为空');
        }


        $params = "appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=".$grant_type;
        $url = "https://api.weixin.qq.com/sns/jscode2session?".$params;


        Log::info('url'.json_encode($url));
        $res = Http::get($url);

        Log::info(json_encode($res));
        $rr = json_decode($res,true);


        if(!empty($rr['openid'])){


            $user = \app\common\model\User::where(['openid'=>$rr['openid'],'id'=>$user_id])->find();

            if(!empty($user)){

                $data['userinfo'] = $user;

                return   $this->success('', $data);
            }

//            $info = \app\common\model\Info::where('user_id',$user['id'])->find();
////
////
//            if(!empty($info)){
//                $data['userinfo']['is_info'] = 2;
//            }
////

   //         $data['userinfo']['is_info'] = 1;
            $data['userinfo']['openid'] = $rr['openid'];
        }else{
            $data['userinfo'] = '';
        }

        Log::info('data==='.json_encode($data));

     return   $this->success('', $data);

    }








//
    /**
     * 手机验证码登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }
//
//    /**
//     * 注册会员
//     *
//     * @param string $username 用户名
//     * @param string $password 密码
//     * @param string $email    邮箱
//     * @param string $mobile   手机号
//     * @param string $code   验证码
//     */
//    public function register()
//    {
//        $username = $this->request->request('username');
//        $password = $this->request->request('password');
//        $email = $this->request->request('email');
//        $mobile = $this->request->request('mobile');
//        $code = $this->request->request('code');
//        if (!$username || !$password) {
//            $this->error(__('Invalid parameters'));
//        }
//        if ($email && !Validate::is($email, "email")) {
//            $this->error(__('Email is incorrect'));
//        }
//        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
//            $this->error(__('Mobile is incorrect'));
//        }
//        $ret = Sms::check($mobile, $code, 'register');
//        if (!$ret) {
//            $this->error(__('Captcha is incorrect'));
//        }
//        $ret = $this->auth->register($username, $password, $email, $mobile, []);
//        if ($ret) {
//            $data = ['userinfo' => $this->auth->getUserinfo()];
//            $this->success(__('Sign up successful'), $data);
//        } else {
//            $this->error($this->auth->getError());
//        }
//    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

//    /**
//     * 修改会员个人信息
//     *
//     * @param string $avatar 头像地址
//     * @param string $username 用户名
//     * @param string $nickname 昵称
//     * @param string $bio 个人简介
//     */
//    public function profile()
//    {
//        $user = $this->auth->getUser();
//        $username = $this->request->request('username');
//        $nickname = $this->request->request('nickname');
//        $bio = $this->request->request('bio');
//        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
//        if ($username) {
//            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
//            if ($exists) {
//                $this->error(__('Username already exists'));
//            }
//            $user->username = $username;
//        }
//        if ($nickname) {
//            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
//            if ($exists) {
//                $this->error(__('Nickname already exists'));
//            }
//            $user->nickname = $nickname;
//        }
//        $user->bio = $bio;
//        $user->avatar = $avatar;
//        $user->save();
//        $this->success();
//    }
//
//    /**
//     * 修改邮箱
//     *
//     * @param string $email 邮箱
//     * @param string $captcha 验证码
//     */
//    public function changeemail()
//    {
//        $user = $this->auth->getUser();
//        $email = $this->request->post('email');
//        $captcha = $this->request->request('captcha');
//        if (!$email || !$captcha) {
//            $this->error(__('Invalid parameters'));
//        }
//        if (!Validate::is($email, "email")) {
//            $this->error(__('Email is incorrect'));
//        }
//        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
//            $this->error(__('Email already exists'));
//        }
//        $result = Ems::check($email, $captcha, 'changeemail');
//        if (!$result) {
//            $this->error(__('Captcha is incorrect'));
//        }
//        $verification = $user->verification;
//        $verification->email = 1;
//        $user->verification = $verification;
//        $user->email = $email;
//        $user->save();
//
//        Ems::flush($email, 'changeemail');
//        $this->success();
//    }
//
//    /**
//     * 修改手机号
//     *
//     * @param string $mobile 手机号
//     * @param string $captcha 验证码
//     */
//    public function changemobile()
//    {
//        $user = $this->auth->getUser();
//        $mobile = $this->request->request('mobile');
//        $captcha = $this->request->request('captcha');
//        if (!$mobile || !$captcha) {
//            $this->error(__('Invalid parameters'));
//        }
//        if (!Validate::regex($mobile, "^1\d{10}$")) {
//            $this->error(__('Mobile is incorrect'));
//        }
//        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
//            $this->error(__('Mobile already exists'));
//        }
//        $result = Sms::check($mobile, $captcha, 'changemobile');
//        if (!$result) {
//            $this->error(__('Captcha is incorrect'));
//        }
//        $verification = $user->verification;
//        $verification->mobile = 1;
//        $user->verification = $verification;
//        $user->mobile = $mobile;
//        $user->save();
//
//        Sms::flush($mobile, 'changemobile');
//        $this->success();
//    }
//
//    /**
//     * 第三方登录
//     *
//     * @param string $platform 平台名称
//     * @param string $code Code码
//     */
//    public function third()
//    {
//        $url = url('user/index');
//        $platform = $this->request->request("platform");
//        $code = $this->request->request("code");
//        $config = get_addon_config('third');
//        if (!$config || !isset($config[$platform])) {
//            $this->error(__('Invalid parameters'));
//        }
//        $app = new \addons\third\library\Application($config);
//        //通过code换access_token和绑定会员
//        $result = $app->{$platform}->getUserInfo(['code' => $code]);
//        if ($result) {
//            $loginret = \addons\third\library\Service::connect($platform, $result);
//            if ($loginret) {
//                $data = [
//                    'userinfo' => $this->auth->getUserinfo(),
//                    'thirdinfo' => $result
//                ];
//                $this->success(__('Logged in successful'), $data);
//            }
//        }
//        $this->error(__('Operation failed'), $url);
//    }
//
//    /**
//     * 重置密码
//     *
//     * @param string $mobile 手机号
//     * @param string $newpassword 新密码
//     * @param string $captcha 验证码
//     */
//    public function resetpwd()
//    {
//        $type = $this->request->request("type");
//        $mobile = $this->request->request("mobile");
//        $email = $this->request->request("email");
//        $newpassword = $this->request->request("newpassword");
//        $captcha = $this->request->request("captcha");
//        if (!$newpassword || !$captcha) {
//            $this->error(__('Invalid parameters'));
//        }
//        if ($type == 'mobile') {
//            if (!Validate::regex($mobile, "^1\d{10}$")) {
//                $this->error(__('Mobile is incorrect'));
//            }
//            $user = \app\common\model\User::getByMobile($mobile);
//            if (!$user) {
//                $this->error(__('User not found'));
//            }
//            $ret = Sms::check($mobile, $captcha, 'resetpwd');
//            if (!$ret) {
//                $this->error(__('Captcha is incorrect'));
//            }
//            Sms::flush($mobile, 'resetpwd');
//        } else {
//            if (!Validate::is($email, "email")) {
//                $this->error(__('Email is incorrect'));
//            }
//            $user = \app\common\model\User::getByEmail($email);
//            if (!$user) {
//                $this->error(__('User not found'));
//            }
//            $ret = Ems::check($email, $captcha, 'resetpwd');
//            if (!$ret) {
//                $this->error(__('Captcha is incorrect'));
//            }
//            Ems::flush($email, 'resetpwd');
//        }
//        //模拟一次登录
//        $this->auth->direct($user->id);
//        $ret = $this->auth->changepwd($newpassword, '', true);
//        if ($ret) {
//            $this->success(__('Reset password successful'));
//        } else {
//            $this->error($this->auth->getError());
//        }
//    }


    //递归
    public function get_attr($a, $pid)
    {

        $tree = array();                                //每次都声明一个新数组用来放子元素
        foreach ($a as $v) {
            if ($v['pid'] == $pid) {                      //匹配子记录
                $v['children'] = $this->get_attr($a, $v['id']); //递归获取子记录
                if ($v['children'] == null) {
                    unset($v['children']);             //如果子元素为空则unset()
                }
                $tree[] = $v;                           //将记录存入新数组
            }
        }
        return $tree;                                  //返回新数组
    }


    /**
     * 列表
     */
    public function categoryList()
    {

        $data = Category::field('id,name,pid')->where(['type'=>'default'])->select();

        $list = $this->get_attr($data, 0);


        return $this->success('', $list);
    }



    /**
     * 列表
     */
    public function dayList()
    {
        $resAdr = model('Config')->field('value')->where(['group' => 'basic', 'name' => 'app_url'])->find();

        $user_id = $this->request->Post('user_id');

        if (empty($user_id)) {
            $this->error(__('用户ID未找到'));
        }

        $user = \app\common\model\User::where('id',$user_id)->findOrFail();
        if (empty($user)) {
            $this->error(__('用户未找到'));
        }

        if($user->category_id >0){

            $data = DayCategory::field('id,c_id,name,pid,description')->where('c_id',$user->category_id)->select();

        }else{
            $data = DayCategory::field('id,c_id,name,pid,description')->select();
        }




       $list['day'] = $this->get_attr($data, 0);

        $list['topics'] =config('site.topics');

        $list['prompt'] = config('site.prompt');
        return $this->success('', $list);
    }



    /**
     * 列表
     */
    public function user_list()
    {

        $user_id = $this->request->Post('user_id');
        $type = $this->request->Post('type');

        if (empty($user_id)) {
            $this->error(__('用户ID未找到'));
        }

        $user = \app\common\model\User::where('id',$user_id)->findOrFail();


        if (empty($user)) {
            $this->error(__('用户未找到'));
        }

        $this->relationSearch = true;

        $list = \app\common\model\User::field('id,avatar,username,mobile,nickname,group_id,category_id')
            ->where(function ($query) use ($user) {

                if ($user->category_id > 0) {
                    $query->Where(['category_id' => $user->category_id]);
                }
                if ($user->group_id == 2) {
                    $query->Where(['group_id' => 1]);
                }else{
                    $query->Where(['group_id' => 2]);
                }
                $query->where(['status' => 'normal']);
            })->order('id', 'desc')
            ->select();


            foreach ($list as &$v) {

                //  is_status = 0未签到，1是已签到
                $v->is_status = UserSignin::where(['user_id' => $v->id, 'type' => $type])->whereTime('last_date', 'd')->count();
                $v->is_leave  = Leave::where(['user_id' => $v->id])->where('time', date("Y-m-d"))->count();
            }




        $this->success('', $list);
    }


    /**
     * 列表
     */
    public function sign()
    {

        $res = $this->request->Post();

        Db::startTrans();
        try {
            //老师签到
//            if($this->auth->group_id == 1 ) {
                if (count($res['user_id']) > 0) {
                    foreach ($res['user_id'] as $k => $v) {

                        $time = strtotime(date('Ymd'));

                        $is_sign = UserSignin::where(['user_id' => $v, 'type' => $res['type'], 'createtime' => ['>=', $time]])->count();


                        if (!empty($v) && $is_sign == 0) {
                            $data['user_id'] = $v;
                            $data['last_date'] = date("Y-m-d H:i");
                            $data['type'] = $res['type'];
                            $data['createtime'] = time();
                            $data['updatetime'] = time();
                            model('user_signin')->insert($data);
                        }

                    }

                    Db::commit();

                }

//            }else{
//
//                $time = strtotime(date('Ymd'));
//
//                $is_sign = UserSignin::where(['user_id' => $this->auth->id, 'type' => $res['type'], 'createtime' => ['>=', $time]])->count();
//
//
//                if($is_sign == 0){
//                    $data['user_id'] = $this->auth->id;
//                    $data['last_date'] = date("Y-m-d H:i");
//                    $data['type'] = $res['type'];
//                    $data['createtime'] = time();
//                    $data['updatetime'] = time();
//                    model('user_signin')->insert($data);
//                    Db::commit();
//                }
//
//            }


        } catch (\Exception $e) {
            DB::rollback();
            return $this->error($e->getMessage());
        }

        return $this->success('签到成功');

    }

    /**
     * 签到列表
     */
    public function signlist()
    {
        $res = $this->request->Post();


        if(empty($res['user_id'])){
            return  $this->error(__('用户ID未找到'));
        }

        $list = Singin::where('user_id',$res['user_id'])
            ->order('createtime', 'desc') ->paginate(10,1);

        return $this->success('',$list);

    }


    /**
     * 学生签到状态
     */
    public function signstatus()
    {
        $res = $this->request->Post();


        if(empty($res['user_id'])){
            return  $this->error(__('用户ID未找到'));
        }

        $list['in'] = Singin::where(['user_id'=>$res['user_id'],'type'=>0])->whereTime('last_date', 'd')->count();
        $list['out'] = Singin::where(['user_id'=>$res['user_id'],'type'=>1])->whereTime('last_date', 'd')->count();

        return $this->success('',$list);

    }


    /**
     * 请假
     */
    public function leave()
    {

        $res = $this->request->Post();

        if(empty($res['user_id'])){

            return    $this->error(__('用户ID未找到'));

        }

        Db::startTrans();
        try {

//            if($this->auth->group_id == 1 && !empty($res['user_id']) ) {
//                $data['user_id'] = $res['user_id'];
//            }else{
//                $data['user_id'] = $this->auth->id;
//            }

            $data['user_id'] =$res['user_id'];
            $data['time'] = $res['time'];
            $data['type'] = $res['type'];
            $data['createtime'] = time();
            $data['smg'] = $res['smg'];
            model('leave')->insert($data);
            Db::commit();

        } catch (\Exception $e) {
            DB::rollback();
            return $this->error($e->getMessage());
        }

        return $this->success('请假已提交');

    }



    /**
     * 班级圈老师发布
     */
    public function growing()
    {

        $res = $this->request->Post();


        if(empty($res['user_id'])){
          return  $this->error(__('用户ID未找到'));
        }

        $user = \app\common\model\User::where('id',$res['user_id'])->find();
        if(empty($user)) {
          return  $this->error(__('用户未找到'));
        }

        if($user->group_id == 2){
           return $this->error(__('学生无权限发布'));
        }

        Db::startTrans();
        try {

            $data['user_id'] = $res['user_id'];
            $data['images'] = $res['images'];
            $data['c_id'] = $user->category_id;
            $data['createtime'] = time();
            $data['content'] = $res['content'];

            model('growing')->insert($data);
            Db::commit();

        } catch (\Exception $e) {
            DB::rollback();
            return $this->error($e->getMessage());
        }

        return $this->success('发布成功');

    }


    /**
     * 学生册老师或学生发布
     */
    public function student_copies()
    {

        $res = $this->request->Post();


        if(empty($res['user_id'])){
             return   $this->error(__('用户ID未找到'));
        }
        $user = \app\common\model\User::where('id',$res['user_id'])->find();
        if(empty($user)) {
            return $this->error(__('用户未找到'));
        }

        Db::startTrans();
        try {

            $data['user_id'] = $res['user_id'];
            $data['images'] = $res['images'];
            $data['c_id'] = $user->category_id;
            $data['createtime'] = time();
            $data['content'] = $res['content'];
            $data['uid'] = $res['uid'];
            model('student_copies')->insert($data);
            Db::commit();

        } catch (\Exception $e) {
            DB::rollback();
            return $this->error($e->getMessage());
        }

        return $this->success('发布成功');

    }



//
//    /**
//     * 查看
//     */
//    public function studentList()
//    {
//
//        $user_id = $this->request->Post('user_id');
//
//        $user = \app\common\model\User::where('id',$user_id)->findOrFail();
//
//
//        $list = StudentCopies::with(['user','Userstudent'])->where('c_id',$user->category_id)
//            ->order('createtime', 'desc') ->paginate(10);
//
//        foreach ($list as $k=>$row) {
//
//            $row->getRelation('user')->visible(['username','nickname','category_id','avatar']);
//
//            foreach ($row->usergrowing  as $kk=>$vv){
//
//                if($vv->to_user_id > 0){
//                    if($vv->to_user_id == $vv->user_id){
//                        $vv->to_nickname = '';
//                    }else{
//                        $vv->to_nickname = \app\common\model\User::where('id',$vv->to_user_id)->value('nickname');
//                    }
//
//                    $vv->nickname = \app\common\model\User::where('id',$vv->user_id)->value('nickname');
//                }
//
//            }
//
//        }
//
//
//        return $this->success('',$list);
//
//
//    }
//
//
//





    /**
     * 评论
     */
    public function addgrowing()
    {

        $res = $this->request->Post();


        if(empty($res['user_id'])){
            return   $this->error(__('用户ID未找到'));
        }

//        $user = \app\common\model\User::where('id',$res['user_id'])->find();
//        if(empty($user)) {
//            return $this->error(__('用户未找到'));
//        }



        Db::startTrans();
        try {


            $data['user_id'] = $res['user_id'];
            $data['to_user_id'] = $res['to_user_id'] ?? 0;
            $data['growing_id'] = $res['id'];
            $data['createtime'] = time();
            $data['content'] = $res['content'] ?? '';

           $dd['id'] =  model('usergrowing')->insertGetId($data);
            Db::commit();

        } catch (\Exception $e) {
            DB::rollback();
            return $this->error($e->getMessage());
        }

        return $this->success('提交成功',$dd);

    }



    /**
     * 评论
     */
    public function delgrowing()
    {

        $res = $this->request->Post();


        if(empty($res['user_id'])){
            return   $this->error(__('用户ID未找到'));
        }

        Db::startTrans();
        try {

            $growing = Usergrowing::where('id',$res['id'])->find();
            if(empty($growing)){
                return   $this->error(__('已删除'));
            }
            $growing->delete();

            Db::commit();

        } catch (\Exception $e) {
            DB::rollback();
            return $this->error($e->getMessage());
        }

        return $this->success('删除成功');

    }



    /**
     * 点赞
     */
    public function addgrowinglike()
    {

        $res = $this->request->Post();


        if(empty($res['user_id'])){
            return   $this->error(__('用户ID未找到'));
        }


        Db::startTrans();
        try {

            $dd = UserGrowingLike::where(['growing_id'=>$res['id'],'user_id'=>$res['user_id']])->find();
            if(empty($dd)){
                $data['user_id'] = $res['user_id'];
                $data['to_user_id'] = $res['to_user_id'] ?? 0;
                $data['growing_id'] = $res['id'];
                $data['createtime'] = time();
                $data['dd'] = $res['dd'] ?? 0;
                model('user_growing_like')->insert($data);
            }else{
                $dd->dd=$res['dd'] ?? 0;
                $dd->createtime = time();
                $dd->save();
            }

            Db::commit();

        } catch (\Exception $e) {
            DB::rollback();
            return $this->error($e->getMessage());
        }

        return $this->success('提交成功');

    }

    /**
     * 评论
     */
    public function addclass_book()
    {

        $res = $this->request->Post();


        if(empty($res['user_id'])){
            return   $this->error(__('用户ID未找到'));
        }


        Db::startTrans();
        try {


            $data['user_id'] = $res['user_id'];
            $data['to_user_id'] = $res['to_user_id'] ?? 0;
            $data['student_id'] = $res['id'];
            $data['createtime'] = time();
            $data['content'] = $res['content'] ?? '';


            $dd['id']  = model('userstudent')->insertGetId($data);
            Db::commit();

        } catch (\Exception $e) {
            DB::rollback();
            return $this->error($e->getMessage());
        }

        return $this->success('提交成功',$dd);

    }



    /**
     * 评论
     */
    public function addclassbooklike()
    {

        $res = $this->request->Post();


        if(empty($res['user_id'])){
            return   $this->error(__('用户ID未找到'));
        }
//        if(empty($res['to_user_id'])){
//            $growing = StudentCopies::where('id',$res['id'])->find();
//
//            $res['to_user_id'] = $growing['user_id'];
//        }

        Db::startTrans();
        try {

            $dd = UserStudentLike::where(['student_id'=>$res['id'],'user_id'=>$res['user_id']])->find();



            if(empty($dd)){
                $data['user_id'] = $res['user_id'];
                $data['to_user_id'] = $res['to_user_id'] ?? 0;
                $data['student_id'] = $res['id'];
                $data['createtime'] = time();
                $data['dd'] = $res['dd'] ?? 0;
                model('user_student_like')->insert($data);
            }else{

                $dd->student_id = $res['id'];
                $dd->dd=$res['dd'] ?? 0;
                $dd->createtime = time();
                $dd->save();
            }

            Db::commit();

        } catch (\Exception $e) {
            DB::rollback();
            return $this->error($e->getMessage());
        }

        return $this->success('提交成功');

    }



    /**
     * 评论
     */
    public function delstudent()
    {

        $res = $this->request->Post();


        if(empty($res['user_id'])){
            return   $this->error(__('用户ID未找到'));
        }


        Db::startTrans();
        try {

            $dd = Userstudent::where(['id'=>$res['id'],'user_id'=>$res['user_id']])->find();
            if(empty($dd)){
                return   $this->error(__('已删除'));
            }

            $dd->delete();


            Db::commit();

        } catch (\Exception $e) {
            DB::rollback();
            return $this->error($e->getMessage());
        }

        return $this->success('删除成功');

    }



}
